/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import entity.EventInfo;
import entity.Registration;
import entity.UserInfo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.servlet.ServletContext;
import model.EventInfoFacade;
import model.RegistrationFacade;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author VietTien
 */
@ManagedBean
@SessionScoped
public class EventController {

    @EJB
    private RegistrationFacade registrationFacade;
    @EJB
    private EventInfoFacade eventInfoFacade;
    private EventInfo current;//Select current row
    private DataModel items = null;//Lay list event
    private List<EventInfo> eventList;
    private DataModel upcommingEvent = null;
    private Date today;
    private String newName;
    private StreamedContent file;
    String fileName;
    private UploadedFile fileImage;
    byte[] buff;

    public void insertAssignmentDetails(FileUploadEvent event) {
        fileImage = event.getFile();
        System.out.println("--// Pick File : " + fileImage);
        JsfUtil.addSuccessMessage(" Upload :"  + fileName + "Success !" );
        //get file name
        fileName = event.getFile().getFileName();
        buff = fileImage.getContents();
        System.out.println("--// Size  : " + fileImage.getSize() + "kB");;
    }

    public UploadedFile getFileImage() {
        return fileImage;
    }

    public void setFileImage(UploadedFile fileUpload) {
        this.fileImage = fileUpload;
    }

    public String getNewName() {
        return newName;
    }

    public void setNewName(String newName) {
        this.newName = newName;
    }

    /** Creates a new instance of EventController */
    public EventController() {

        today = new Date();
    }

    public Date getToday() {
        return new Date();
    }

    public EventInfo getCurrent() {
        return current;
    }

    public void setCurrent(EventInfo current) {
        this.current = current;
    }

    public List<EventInfo> getEventList() {
        return eventList;
    }

    public void setEventList(List<EventInfo> eventList) {
        this.eventList = eventList;
    }
    private DataModel itemsAdmin = null;
    private DataModel itemsUser = null;

    public DataModel getItems() {
        //get user from session
        UserInfo user = (UserInfo) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
        if (user != null) { //user has logged into system
            if (user.getIsAdmin()) {  //if user is admin
                itemsUser = null;
                if (itemsAdmin == null) {
                    itemsAdmin = new ListDataModel(eventInfoFacade.showEvent());
                }
                items = itemsAdmin;
            } else {
                itemsAdmin = null;
                if (itemsUser == null) {
                    itemsUser = new ListDataModel(eventInfoFacade.showHomeEvent());
                }
                items = itemsUser;
            }
        }
        if (user == null) {
            if (items == null) {
                items = new ListDataModel(eventInfoFacade.showHomeEvent());
            }
            itemsAdmin = null;
        }

        return items;
    }

    public void setItems(DataModel items) {
        this.items = items;
    }

    private void reload() {
        items = null;
        itemsAdmin = null;
        itemsEventReg = null;
    }

    public String create() {
        try {
            String eventName = current.getEventName().trim();
            eventName = eventName.replaceAll("\\s+", " ");
            if (eventInfoFacade.findByName(eventName).size() <= 0) {

                FileOutputStream fos = null;

                String realPath = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath("/");


                if (this.current.getImageEvent() == null) {
                    current.setImageEvent(fileName);

                }
                try {
                    if (fileName == null) {
                        JsfUtil.addErrorMessage("Please choose an image of new event!!!");
                        return null;
                    }
                    File f = new File(realPath + "//resources//css//images//" + fileName);
                    System.out.println("File" + f);
                    if (!f.exists()) {
                        f.createNewFile();
                    }
                    fos = new FileOutputStream(f);
                    fos.write(buff);
                    fos.close();
                    if (JsfUtil.isSpacesOnly(current.getEventName().trim())) {
                        JsfUtil.addErrorMessage("Please input event name field.");
                        return null;
                    }
                    if (JsfUtil.isSpacesOnly(current.getEventTitle().trim())) {
                        JsfUtil.addErrorMessage("Please input title event field.");
                        return null;
                    }
                    if (JsfUtil.isSpacesOnly(current.getDescriptionEvent().trim())) {
                        JsfUtil.addErrorMessage("Please input description field.");
                        return null;
                    }
                    if (current.getMaxPlayer() < 1) {
                        JsfUtil.addErrorMessage("Max player must be more than 1 player");
                        return null;
                    }
                    if (current.getStartReg().after(current.getEndReg())) {
                        JsfUtil.addErrorMessage("Start Registration must be larger than end registration !");
                        return null;
                    }
                    if (current.getEndReg().after(current.getStartEvent())) {
                        JsfUtil.addErrorMessage("End registration must be larger than start event !");
                        return null;
                    }
                    if (current.getStartEvent().after(current.getFinishEvent())) {
                        JsfUtil.addErrorMessage("Start event must be larger than finish event !");
                        return null;
                    }
                    current.getEndReg().setHours(23);
                    current.getEndReg().setMinutes(59);
                    current.getEndReg().setSeconds(59);
                    current.setMinPlayer(0);
                    current.setIsDelete(false);
                    current.setEventName(eventName);
                    current.setEventTitle(current.getEventTitle().trim());
                    current.setDescriptionEvent(current.getDescriptionEvent().trim());
                    eventInfoFacade.create(current);
                    JsfUtil.addSuccessMessage("Event was successfully created.");
                    reload();
                    return "AddEventSuccess";

                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }

            } else {
                JsfUtil.addErrorMessage("Event name already exist !");
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, "Error in action !");
            return null;
        }
    }

    public EventInfo getSelected() {
        if (current == null) {
            current = new EventInfo();
        }
        return current;
    }

    public String prepareView() {
        current = (EventInfo) getItems().getRowData();
        return "/Event/ViewEvent.xhtml?faces-redirect=true";
    }

    public String prepareEdit() {

        current = (EventInfo) getItems().getRowData();
        newName = current.getEventName();
        return "EditEvent";
    }

    public String prepareEditInView() {

        current = getSelected();
        return "EditEvent";
    }

    public String prepareCreate() {
        current = new EventInfo();
        return "AddNewEvent";
    }

    public String update() {
        try {
            String eventName = newName.trim();
            eventName = eventName.replaceAll("\\s+", " ");
            if (eventInfoFacade.findByNameExceptOne(current.getEventName().trim(), eventName.trim()).size() <= 0) {
                if (fileName != null) {
                    FileOutputStream fos = null;
                    String realPath = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath("/");
                    current.setImageEvent(fileName);
                    File f = new File(realPath + "//resources//css//images//" + fileName);
                    if (!f.exists()) {
                        f.createNewFile();
                    }
                    fos = new FileOutputStream(f);
                    fos.write(buff);
                    fos.close();
                }
                if (JsfUtil.isSpacesOnly(newName.trim())) {
                    JsfUtil.addErrorMessage("Please input event name field.");
                    return null;
                }
                if (JsfUtil.isSpacesOnly(current.getEventTitle().trim())) {
                    JsfUtil.addErrorMessage("Please input title event field.");
                    return null;
                }
                if (JsfUtil.isSpacesOnly(current.getDescriptionEvent().trim())) {
                    JsfUtil.addErrorMessage("Please input description field.");
                    return null;
                }
                if (current.getMaxPlayer() < 1) {
                    JsfUtil.addErrorMessage("Max player must be more than 1 player");
                    return null;
                }
                if (current.getStartReg().after(current.getEndReg())) {
                    JsfUtil.addErrorMessage("Start Registration must be larger than end registration !");
                    return null;
                }
                if (current.getEndReg().after(current.getStartEvent())) {
                    JsfUtil.addErrorMessage("End registration must be larger than start event !");
                    return null;
                }
                if (current.getStartEvent().after(current.getFinishEvent())) {
                    JsfUtil.addErrorMessage("Start event must be larger than finish event !");
                    return null;
                }
                current.setEventName(eventName.trim());
                current.setEventTitle(current.getEventTitle().trim());
                current.setDescriptionEvent(current.getDescriptionEvent().trim());
                eventInfoFacade.edit(current);
                reload();
                JsfUtil.addSuccessMessage("Event was successfully updated");
                return "UpdateSuccess";
            } else {
                newName = eventName;
                JsfUtil.addErrorMessage("Event name already exist !");
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, "Error in action !");
            return null;
        }
    }

    public String restore() {
        try {
            current = (EventInfo) getItems().getRowData();
            current.setIsDelete(false);
            eventInfoFacade.edit(current);
            JsfUtil.addSuccessMessage("Event was successfully active");
            reload();
            return "event";
        } catch (Exception e) {
            System.out.println(e.toString());
            JsfUtil.addErrorMessage(e, "Error in delete action !");
            return null;
        }
    }

    public String delete() {
        try {
            current = (EventInfo) getItems().getRowData();
            current.setIsDelete(true);
            eventInfoFacade.edit(current);
            JsfUtil.addSuccessMessage("Event was successfully deactive");
            reload();
            return "event";
        } catch (Exception e) {
            System.out.println(e.toString());
            JsfUtil.addErrorMessage(e, "Error in delete action !");
            return null;
        }
    }

    public String cancelAddEvent() {
        reload();
        return "CancelAddEvent";
    }

    public String cancelEditEvent() {
        reload();
        return "CancelEditEvent";
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public StreamedContent getFile() {
        InputStream stream = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/fileDownload/" + fileName);
        file = new DefaultStreamedContent(stream, "image/jpg", fileName);

        return file;
    }

    public void setFile(StreamedContent file) {
        this.file = file;
    }
    private List<EventInfo> itemsEventReg;

    public List<EventInfo> getItemsEventReg() {
        if (itemsEventReg == null) {
            itemsEventReg = eventInfoFacade.getEventReg();
        }
        return itemsEventReg;
    }

    public void setItemsEventReg(List<EventInfo> itemsEventReg) {
        this.itemsEventReg = itemsEventReg;
    }

    public int countReg(List<Registration> lstReg) {
        int count = 0;
        for (Registration reg : lstReg) {
            if (reg.getCancelTime() == null) {
                count++;
            }
        }
        return count;
    }

    public boolean checkControlEvent(EventInfo evt) {
        if (registrationFacade.findEventHasOneParticipate(evt)) {
            return true;
        }
        return false;
    }
}
